package com.iltgcl.echovoicedemo.ui.main

import android.os.Bundle
import android.view.*
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.iltgcl.echovoicedemo.R
import com.iltgcl.echovoicedemo.databinding.FragmentMainBinding
import com.iltgcl.echovoicedemo.ui.base.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber

@AndroidEntryPoint
class MainFragment : BaseFragment() {

    private val viewModel:MainViewModel by viewModels()
    private lateinit var binding:FragmentMainBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        setHasOptionsMenu(true)
        binding = FragmentMainBinding.inflate(inflater, container, false).apply {
            lifecycleOwner = this@MainFragment
            vm = viewModel
            executePendingBindings()
        }
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setupSnackbar(viewModel.snackbarText)
        viewModel.initialize.observe(viewLifecycleOwner, {
            if (it) {
                viewModel.showSnackbarMessage(R.string.echo_voice_init_success)
            } else {
                viewModel.showSnackbarMessage(R.string.echo_voice_init_fail)
            }
        })
        viewModel.start()
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu_main, menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when(item.itemId) {
            R.id.action_settings -> {
                Timber.d("======== click settings !")
                findNavController().navigate(R.id.action_MainFragment_to_SettingsFragment)
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}